package com.kingbook.api.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingbook.common.utils.DateUtils;
import com.kingbook.common.utils.StringUtils;
import com.kingbook.core.annotations.ContainProperties;
import com.kingbook.core.auth.LoginManager;
import com.kingbook.core.result.JSONPageResult;
import com.kingbook.core.result.JSONResult;
import com.kingbook.services.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.Map;

import static com.kingbook.common.enums.DateFormatEnum.DATE;
import static com.kingbook.core.auth.LoginManager.AUTH;

/**
 * @Author Bucky
 * @Date 2019-12-08 17:18:13
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("reservation")
public class ReservationRest {

    @Autowired
    ReservationService reservationService;
    @Autowired
    CustomerService customerService;
    @Autowired
    DriverService driverService;
    @Autowired
    VehicleService vehicleService;
    @Autowired
    PartnerService partnerService;
    @Autowired
    WorkspaceService workspaceService;
    @Autowired
    TonsService tonsService;

    @PutMapping
    @ContainProperties({"workDate", "useType", "address", "tons"})
    public JSONResult save(@RequestBody Map<String, Object> param, @RequestHeader(name = AUTH) String auth) {
        int mid = LoginManager.getMid(auth);
        int id = MapUtils.getIntValue(param, "id");
        param.put("mid", mid);
        String[] wd = MapUtils.getString(param, "workDate").split(" ");
        param.put("workDate", wd[0]);
        param.put("workDurationAm", wd[1] + "-" + wd[2]);
        param.put("workDurationPm", "");
        int chargeType = MapUtils.getIntValue(param, "chargeType");
        int amount = MapUtils.getIntValue(param, "amount");
        float chargeNum = MapUtils.getIntValue(param, "chargeNum");
        if (amount == 0 && chargeNum == 0) {
            param.put("chargeType", 0);
        }
        if (MapUtils.getIntValue(param, "useType") == 1) {
            int cid = customerService.getCustomerId(mid, MapUtils.getString(param, "customer"), true);
            param.put("wid", workspaceService.getWorkspaceIdByCid(mid, cid, MapUtils.getString(param, "address")));
            param.put("reserverCid", cid);
            param.put("reserverPid", 0);
        } else {
            int pid = partnerService.getPartnerId(mid, MapUtils.getString(param, "partner"), true);
            param.put("wid", workspaceService.getWorkspaceIdByPid(mid, pid, MapUtils.getString(param, "address")));
            param.put("reserverCid", 0);
            param.put("reserverPid", pid);
        }
        int allotType = MapUtils.getIntValue(param, "allotType");
        String plateNo = MapUtils.getString(param, "plateNo");
        String allotPartner = MapUtils.getString(param, "allotPartner");
        if (allotType == 1 && StringUtils.isNotEmpty(plateNo)) {
            param.put("vid", vehicleService.getVehicleId(mid, 0, plateNo));
            param.put("allotPid", 0);
        } else if (allotType == 2 && StringUtils.isNotEmpty(allotPartner)) {
            param.put("vid", 0);
            param.put("allotPid", partnerService.getPartnerId(mid, allotPartner, true));
        } else {
            param.remove("allotType");
        }
        if (id > 0)
            return reservationService.modify(param);
        return reservationService.save(param);
    }


    @PostMapping("pages")
    @ContainProperties({"pageNo", "pageSize"})
    public JSONResult queryForPages(@RequestBody Map<String, Object> param, @RequestHeader(name = AUTH) String auth) throws ParseException {
        int mid = LoginManager.getMid(auth);
        param.put("mid", mid);
        JSONArray array = new JSONArray();
        String date, today = DateUtils.format(DateUtils.now(), DATE);
        String wd, dur;
        JSONPageResult orders = reservationService.queryForPages(param);
        JSONArray orderArr = orders.getData();
        for (int i = 0; i < orderArr.size(); i++) {
            JSONObject order = orderArr.getJSONObject(i);
            wd = order.getString("workDate");
            dur = order.getString("workDurationAm");
            boolean past = DateUtils.parse(wd + " " + dur.split("-")[0] + ":00").before(DateUtils.now());
            date = DateUtils.format(wd, DATE);
            if (today.equals(date)) {
                date = "今日";
            } else {
                String[] d = date.split("-");
                date = d[1] + "/" + d[2];
            }
            int allot = order.getIntValue("allotType");
            int chargeType = order.getIntValue("chargeType");
            String allotStr = "未分配";
            if (allot == 1) {
                allotStr = "分配:" + order.getString("plateNo");
            } else if (allot == 2) {
                allotStr = "分配:" + order.getString("allotPartner");
            }
            JSONObject json = new JSONObject();
            json.put("id", order.getIntValue("id"));
            json.put("icon", past ? "past" : "reserved");      //计算是否超时
            json.put("workDate", date);
            json.put("chargeTypeColor", order.getIntValue("chargeType") == 1 ? "red" : "green");
            json.put("amount", "￥" + order.getIntValue("amount"));
            json.put("chargeNum", order.getFloatValue("chargeNum") == 0 ? "" : order.getString("chargeNum").replace(".0", "") + "个班");
            Integer jib = order.getInteger("jib");
            if (order.getIntValue("allotType") == 1) {
                json.put("title", order.getString("plateNo") + "  " + order.getString("tons") + "T" + (jib != null && jib > 0 ? "-" + jib : ""));
            } else
                json.put("title", "【外派】 " + order.getString("allotPartner") + "  " + order.getString("tons") + "T" + (jib != null && jib > 0 ? "-" + jib : ""));

            json.put("owner", "预约时间:"+ " " + dur);
            json.put("desc", order.getString("customer") + order.getString("partner") + " " + order.getString("address"));
            array.add(json);
        }
        orders.setData(array);
        return orders;
    }

    @DeleteMapping("{id}")
    public JSONResult remove(@PathVariable int id, @RequestHeader(name = AUTH) String auth) {
        return reservationService.remove(id, LoginManager.getMid(auth));
    }

    @GetMapping("{id}")
    public JSONResult find(@PathVariable int id, @RequestHeader(name = AUTH) String auth) {
        JSONResult r = reservationService.find(id, LoginManager.getMid(auth));
        if (r.isSuccess() && r.getCount() > 0) {
            JSONObject j = r.getData().getJSONObject(0);
            String date = DateUtils.format(j.getString("workDate"), DATE);
            String[] d = date.split("-");
            String[] t = j.getString("workDurationAm").split("-");
            j.put("workDate", date + " " + t[0] + " " + t[1]);
            j.put("workDateStr", d[0] + "." + d[1] + "." + d[2] + "  " + t[0] + "-" + t[1]);
            j.put("tons", j.getString("tons"));
        }
        return r;
    }

    @PostMapping("query")
    public JSONResult query(@RequestBody Map<String, Object> param, @RequestHeader(name = AUTH) String auth) {
        param.put("mid", LoginManager.getMid(auth));
        return reservationService.query(param);
    }

}
